package com.wanmait.spacesys.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wanmait.spacesys.dao.UserinfoDAO;
import com.wanmait.spacesys.vo.Userinfo;

@WebFilter("/*")
public class UserAutoLoginFilter implements Filter {
			UserinfoDAO userinfoDAO = new UserinfoDAO();
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 强转
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession HS = req.getSession();
		Object o = HS.getAttribute("userinfo");
		if (o != null) {
			chain.doFilter(request, response);
		} else {
			Cookie[] cookies = req.getCookies();
			if (cookies != null) {
				String username = "";
				String password = "";
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals("username")) {
						username = cookie.getValue();
					}
					if (cookie.getName().equals("password")) {
						password = cookie.getValue();
					}
				}
				
				if(!username.isEmpty()&&!password.isEmpty()) {
					Userinfo userinfo = new Userinfo();
					userinfo.setUsername(username);
					userinfo.setPassword(password);
					Userinfo userLogin =  userinfoDAO.isRight(username, password);
					if(userLogin==null) {
						res.sendRedirect(req.getContextPath()+"/web/userLogin.jsp"	);
					}
					else {
						HS.setAttribute("userinfo",userLogin);
						chain.doFilter(request, response);
					}
				}
				else {
					chain.doFilter(request, response);
				}
			}
			else {
				chain.doFilter(request, response);
			}
		}
	}
}
